package com.zkyc.framework.website.strategy.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zkyc.framework.common.constant.NumberConstant;
import com.zkyc.framework.common.exception.ResultCode;
import com.zkyc.framework.common.mapper.ColumnDataClickRateMapper;
import com.zkyc.framework.common.pojo.*;
import com.zkyc.framework.common.utils.WebsiteUtil;
import com.zkyc.framework.common.vo.ResultVO;
import com.zkyc.framework.common.vo.website.ColumnDataPageVo;
import com.zkyc.framework.common.vo.website.ReplaceContentVo;
import com.zkyc.framework.common.vo.website.WebContentVo;
import com.zkyc.framework.website.config.MathcingConfig;
import com.zkyc.framework.website.mapper.*;
import com.zkyc.framework.website.strategy.StrategyEnum;
import com.zkyc.framework.website.strategy.StrategyService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.zkyc.framework.website.service.impl.AssociationServiceImpl.getAssociationTree;

/**
 * 除官网外
 */
@Service
public class MikuContentStrategyImpl implements StrategyService {

    @Autowired
    private MoudleMapper moudleMapper;
    @Autowired
    private ColumnMapper columnMapper;
    @Autowired
    private ColumnDataMapper columnDataMapper;
    @Autowired
    private ColumnDataRefMediaTagMapper refMediaTagMapper;
    @Autowired
    private ColumnDataClickRateMapper dataClickRateMapper;
    @Autowired
    private AssociationMapper associationMapper;

    @Override
    public Integer fetchKey() {
        return StrategyEnum.Miku.getKey();
    }

    @Override
    public ResultVO queryList() {
        List<Association> associations = associationMapper.selectList(null);
        // handleAssociationFiles(associations);
        List<Association> associationTree = getAssociationTree(associations);
        return ResultVO.data(associationTree);
    }

    @Override
    public ResultVO globalList(ColumnDataPageVo columnDataPageVo) {
        IPage<ColumnData> page = new Page<>(columnDataPageVo.getCurrent(), columnDataPageVo.getSize());
        // 只需要已发布的
        columnDataPageVo.setStatus(NumberConstant.NUMBER_1);

        LambdaQueryWrapper<ColumnData> columnDataLqw = new LambdaQueryWrapper<>();
        preQueryColumnData(WebsiteUtil.getWebsiteId(), columnDataLqw);
        String content = columnDataPageVo.getIntroduce();
        if (StringUtils.isNotBlank(content)) {
            columnDataLqw.and(wrapper -> wrapper.like(ColumnData::getOriginalContent, content).or().like(ColumnData::getTitle, content));
        }
        preQueryColumnData(columnDataLqw, columnDataPageVo);
        // todo 根据什么排序
        columnDataLqw.orderByDesc(ColumnData::getPublishTime);
        IPage<ColumnData> columnDataIPage = columnDataMapper.selectPage(page, columnDataLqw);
        handleColumnDataClickPlus(columnDataIPage.getRecords(), columnDataIPage.getRecords().stream().map(ColumnData::getId).collect(Collectors.toList()));
        // todo 转vo
        List<WebContentVo> webContentVoList = columnDataIPage.getRecords().stream().map(columnData -> {
            WebContentVo webContentVo = new WebContentVo();
            BeanUtils.copyProperties(columnData, webContentVo);
            webContentVo.setContent(columnData.getIntroduce());
            webContentVo.setContentTitle(columnData.getTitle());
            webContentVo.setClickRate(columnData.getHitNumber());
            return webContentVo;
        }).collect(Collectors.toList());
        IPage<WebContentVo> webContentVoPage = new Page<>();
        BeanUtils.copyProperties(columnDataIPage, webContentVoPage);
        webContentVoPage.setRecords(webContentVoList);
        return ResultVO.data(webContentVoPage);
    }

    @Override
    public ResultVO replaceContent(ReplaceContentVo replaceContentVo) {
        String sourceTextIllegal = judgeReplaceAble(replaceContentVo.getSourceText());
        if (sourceTextIllegal != null) {
            return ResultVO.fail("包含不能被替换词" + sourceTextIllegal);
        }
        String targetTextIllegal = judgeReplaceAble(replaceContentVo.getTargetText());
        if (targetTextIllegal != null) {
            return ResultVO.fail("包含不能被替换词" + targetTextIllegal);
        }
        List<Integer> contentIds = replaceContentVo.getContentIds();
        if (contentIds.size() < 1) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        columnDataMapper.replaceContent(replaceContentVo.getSourceText(), replaceContentVo.getTargetText(), replaceContentVo.getContentIds());
        return ResultVO.success(ResultCode.SUCCESS);
    }

    private String judgeReplaceAble(String text) {
        if (StringUtils.isNotBlank(text)) {
            boolean contains = MathcingConfig.completeMatchingSet.contains(text);
            if (contains) {
                return text;
            }
            for (String fuzzyWord : MathcingConfig.fuzzyMatchingSet) {
                if (text.contains(fuzzyWord)) {
                    return fuzzyWord;
                }
            }
        }
        return null;
    }

    private void preQueryColumnData(String websiteId, LambdaQueryWrapper<ColumnData> queryWrapper) {
        // todo 只需要查各个网站columnType为2的栏目
        // 首先查该网站有哪些模块
        List<Integer> moudleIdList = moudleMapper.queryMoudleByWebsiteIdPlus(Integer.valueOf(websiteId));
        // 再查这些模块下有哪些columnType为2的栏目的id
        if (CollectionUtils.isEmpty(moudleIdList)) {
            queryWrapper.eq(ColumnData::getColumnId, NumberConstant.NUMBER_0);
            return;
        }
        LambdaQueryWrapper<Column> columnLqw = new LambdaQueryWrapper<>();
        // 只需要查id
        columnLqw.select(Column::getId);
        columnLqw.in(Column::getMoudleId, moudleIdList);
        columnLqw.eq(Column::getColumnType, NumberConstant.NUMBER_2);
        List<Column> columnList = columnMapper.selectList(columnLqw);
        List<Integer> columnIdList = columnList.stream().map(Column::getId).collect(Collectors.toList());
        // 拼接条件
        if (CollectionUtils.isEmpty(columnIdList)) {
            queryWrapper.eq(ColumnData::getColumnId, NumberConstant.NUMBER_0);
            return;
        }
        queryWrapper.in(ColumnData::getColumnId, columnIdList);
    }

    private void preQueryColumnData(LambdaQueryWrapper<ColumnData> columnDataLqw, ColumnDataPageVo columnDataPageVo) {
        // 状态
        columnDataLqw.eq(Objects.nonNull(columnDataPageVo.getStatus()), ColumnData::getStatus, columnDataPageVo.getStatus());
        // 组织或协会
        columnDataLqw.eq(Objects.nonNull(columnDataPageVo.getCenterId()), ColumnData::getCenterId, columnDataPageVo.getCenterId());
        // 发布时间
        columnDataLqw.ge(Objects.nonNull(columnDataPageVo.getBeginDate()), ColumnData::getPublishTime, columnDataPageVo.getBeginDate());
        columnDataLqw.le(Objects.nonNull(columnDataPageVo.getEndDate()), ColumnData::getPublishTime, columnDataPageVo.getEndDate());
        // 稿件id
        columnDataLqw.eq(Objects.nonNull(columnDataPageVo.getId()), ColumnData::getId, columnDataPageVo.getId());
        // 创建人
        columnDataLqw.like(StringUtils.isNotBlank(columnDataPageVo.getCreatedBy()), ColumnData::getCreatedBy, columnDataPageVo.getCreatedBy());
        // 标题
        columnDataLqw.like(StringUtils.isNotBlank(columnDataPageVo.getTitle()), ColumnData::getTitle, columnDataPageVo.getTitle());
        // 标签
        if (!CollectionUtils.isEmpty(columnDataPageVo.getTagId())) {
            List<List<Integer>> tagId = columnDataPageVo.getTagId();
            Integer mediaTagId = tagId.get(0).get(0);
            LambdaQueryWrapper<ColumnDataRefMediaTag> dataRefMediaTagLqw = new LambdaQueryWrapper<>();
            // 只需要查columnDataId
            dataRefMediaTagLqw.select(ColumnDataRefMediaTag::getColumnDataId);
            dataRefMediaTagLqw.eq(ColumnDataRefMediaTag::getMediaTagId, mediaTagId);
            List<ColumnDataRefMediaTag> columnDataRefMediaTags = refMediaTagMapper.selectList(dataRefMediaTagLqw);
            List<Integer> columnDataIdList = columnDataRefMediaTags.stream().map(ColumnDataRefMediaTag::getColumnDataId).collect(Collectors.toList());
            // 不为空才需要拼接,为空则拼接查询不到结果的条件
            if (!CollectionUtils.isEmpty(columnDataIdList)) {
                columnDataLqw.in(ColumnData::getId, columnDataIdList);
            } else {
                columnDataLqw.eq(ColumnData::getId, NumberConstant.NUMBER_0);
            }
        }
    }

    private void handleColumnDataClickPlus(List<ColumnData> columnDataList, List<Integer> columnDataIdList) {
        if (CollectionUtils.isEmpty(columnDataIdList)) {
            return;
        }
        List<ColumnDataClickRate> dataClickRateList = dataClickRateMapper.selectRecent(columnDataIdList);
        Map<Integer, Integer> columnDataClickMap = dataClickRateList.stream().collect(Collectors.toMap(ColumnDataClickRate::getColumnDataId, ColumnDataClickRate::getClickRateTotal));
        columnDataList.forEach(columnData -> {
            Integer hitNumber = columnDataClickMap.get(columnData.getId());
            if (hitNumber == null) {
                columnData.setHitNumber(NumberConstant.NUMBER_0);
                return;
            }
            columnData.setHitNumber(hitNumber);
        });
    }
}
